package com.wrupple.muba.catalogs.server.service.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import com.wrupple.muba.catalogs.server.service.CatalogSummaryBuilder;
import com.wrupple.muba.catalogs.server.service.CatalogTokenInterpret;
import com.wrupple.vegetate.domain.CatalogDescriptor;
import com.wrupple.vegetate.domain.CatalogObject;
import com.wrupple.vegetate.domain.FieldDescriptor;
import com.wrupple.vegetate.domain.SummaryCatalogResponse;
import com.wrupple.vegetate.domain.exceptions.BussinessLayerException;
import com.wrupple.vegetate.domain.exceptions.DataLayerException;

public class ColumnGroupingSummary implements CatalogSummaryBuilder {

	CatalogTokenInterpret dao;

	public ColumnGroupingSummary(CatalogTokenInterpret dao) {
		super();
		this.dao = dao;
	}

	@Override
	public List<CatalogObject> createSummary(List<CatalogObject> list,
			String catalogid, boolean summaryFieldsOnly)
			throws BussinessLayerException, DataLayerException {
		CatalogDescriptor descriptor = dao.getDescriptorForName(catalogid);
		Collection<String> fields = descriptor.getFieldNames();
		SummaryCatalogResponse regreso = new SummaryCatalogResponse();
		HashMap<String, List<Object>> contents = new HashMap<String, List<Object>>();

		String fieldId;
		Object fieldValue;
		List<Object> fieldContents;
		BeanWrapper wrapper;
		FieldDescriptor field;
		for (String fieldid : fields) {
			field = descriptor.getFieldDescriptor(fieldid);
			if (!summaryFieldsOnly || field.isSummary()) {
				fieldContents = new ArrayList<Object>(list.size());
				fieldId = field.getId();

				for (CatalogObject object : list) {
					wrapper = new BeanWrapperImpl(object);
					fieldValue = wrapper.getPropertyValue(fieldId);
					fieldContents.add(fieldValue);
				}

				contents.put(fieldId, fieldContents);

			}
		}

		regreso.setContents(contents);
		List singletonList = Collections.singletonList(regreso);
		return singletonList;
	}


}
